import {Animation, director, Label, Node} from 'cc';
import {PrefabManager} from "db://assets/scripts/common/PrefabManager";
import {PrefabDefs} from "db://assets/scripts/defs/PrefabDefs";

export class FloatingTextManager {

    /**
     * 显示飘字
     * @param text 飘字内容
     * @param duration 持续时间，单位秒，默认为3秒
     */
    public static showText(text: string, duration: number = 3): void {

        this._showText(text, duration);
    }

    private static _showText(text: string, duration: number = 3): void {

        let node: Node = PrefabManager.instantiate(PrefabDefs.FloatTextPref, director.getScene().getChildByName("Canvas"));
        // 设置飘字内容和初始位置
        const label = node.getChildByName("Text").getComponent(Label);
        if (label) {
            label.string = text;
        }

        node.getComponent(Animation).on(Animation.EventType.FINISHED, () => this._finishAnimationEnter(node, duration), this);

        node.getComponent(Animation).play('FloatTextEnter');

    }

    private static _finishAnimationEnter(node: Node, duration: number): void {
        setTimeout(() => {
            node.getComponent(Animation).on(Animation.EventType.FINISHED, () => this._finishAnimationLeave(node), this);
            node.getComponent(Animation).play('FloatTextLeave');
        }, duration * 1000);
    }
    private static _finishAnimationLeave(node: Node): void {
        node.removeFromParent();
    }

}


